local M = {}
local json = require("json")
-- 带有属性功能的表
function M.newproperties()
	local t = {}

	local getters =  {}
	local setters = {}

	t.getters = getters

	-- TODO 暂时没有考虑self的问题
	t.__index = function(self, key)
		local getter = getters[key]

		if getter then
			if type(getter) == "table" then
				return getter
			elseif type(getter) == "function" then
				return getter(self, key)
			end
		end
	end

	-- TODO 暂时没有考虑self的问题
	t.__newindex = function(self, key, value)
		local settter = setters[key]
		if settter then
			if type(setter) == "table" then
				return setter
			else
				return setters[key](self, key, value)
			end
		end
	end

	-- 设置对应属性
	function t:setProperty(key, getter, setter)
		getters[key] = getter
		setters[key] = setter
	end

	function t:setTableProperty(key, t1)
		getters[key] = t1
		setters[key] = t1
	end

	local function copyProps(tOri, tDest)
		for k, v in pairs(tOri.getters) do
			local value = tOri[k]
			if type(value) == "table" and value.getters then
				print(value)
				tDest[k] = {}
				copyProps(value, tDest[k])
			else
				print(k, value)
				tDest[k] = value
			end
		end

		--return test
	end

	-- 此方法主要是给编辑器用的
	function t:properties2json()
		local t1 = {}
		copyProps(self, t1)
		return json.encode(t1)
	end

	setmetatable(t, t)

	return t
end

local function test()

	local t1 = {
		ele = 2,
		path = {
			x1 = 0,
		}
	}

	local prop = M.newproperties()

	prop:setProperty(
		"ele",
		function(self, key)
			return t1[key]
		end,
		function(self, key, value)
			t1[key] = value
		end
	)

	local path = M.newproperties()

	path:setProperty(
		"x1",
		function(self, key)
			return t1.path[key]
		end,
		function(self, key, value)
			t1.path[key] = value
		end
	)
	path:setProperty(
			"x2",
			function(self, key)
				return 2
			end,
			function(self, key, value)
				return 0
			end
	)

	prop:setTableProperty("path", path)
	print(path)
	print(prop:properties2json())
end

test()


return M